package com.wyz.util;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;

import javax.imageio.ImageIO;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

public class HutoolCaptchaUtil {
    private static HashMap<String,String> checkCodeMap = new HashMap<>();

    /**
     * 产生验证码
     * @return 验证码Base64编码
     */
public static String generateCaptcha(String uuid) {
    CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(80, 25, 4, 20);
    String generatedCaptcha = captcha.getCode(); // 获取验证码字符串
    System.out.println("验证码："+generatedCaptcha);
    try {
        byte[] imageData = captcha.getImageBytes();
        // 将验证码图片数据转换为Base64编码
        String base64Image = "data:image/jpg;base64," + Base64.getEncoder().encodeToString(imageData);
        checkCodeMap.put(uuid, generatedCaptcha);
        return base64Image;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

    /**
     * 获取验证码
     * @param uuid 验证码UUID
     * @return 验证码
     */
    public static String getCheckCode(String uuid) {
        return checkCodeMap.get(uuid);
    }

    /**
     * 移除验证码
     * @param uuid 验证码UUID
     */
    public static void removeCheckCode(String uuid) {
        checkCodeMap.remove(uuid);
    }

    public static void main(String[] args) {
        String uuid = UUID.randomUUID().toString();
        String imageData = generateCaptcha(uuid);
        String checkCode = getCheckCode(uuid);
        System.out.println(imageData);
        System.out.println(checkCode);
    }
}
